package com.greateamd.timetableasy.client.mvc.view.crud.university;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Widget;
import com.greateamd.timetableasy.client.mvc.model.Model;
import com.greateamd.timetableasy.client.services.university.UniversityService;
import com.greateamd.timetableasy.client.services.university.UniversityServiceAsync;
import com.greateamd.timetableasy.client.services.util.ServerCall;
import com.greateamd.timetableasy.client.widgets.MessagePopupPanel;
import com.greateamd.timetableasy.client.widgets.university.UniversityListBox;
import com.greateamd.timetableasy.client.widgets.university.UniversityPanel;
import com.greateamd.timetableasy.domain.User;

public class EditUniversityPage <M extends Model> extends IEditUniversityPage<M>{

	private final UniversityServiceAsync userService = GWT.create(UniversityService.class);

	@UiTemplate("EditUniversityPage.ui.xml")
	interface EditUserPageUIBinder extends UiBinder<Widget, EditUniversityPage> {}
	private static EditUserPageUIBinder uiBinder = GWT.create(EditUserPageUIBinder.class);

	@UiField UniversityListBox listOfUniversities;
	@UiField UniversityPanel panel;
	@UiField Button submitBt;
	
	/**
	 * Constructor
	 */
	public EditUniversityPage() {
	    initWidget(uiBinder.createAndBindUi(this));
	}
	
	@UiHandler("listOfUniversities")
	void onUniversitySelectedChange(ChangeEvent e){
		panel.setUniversity(listOfUniversities.getSelectedUniversity());
	}
	
	@Override
	public Widget getWidgetPage() {
		return this;
	}

	@Override
	public void setUser(User user) {
	}


	//---------------------------------------------------------------------
	//-------------------------- UI action
	
	
	//---------------------------------------------------------------------
	//-------------------------- Handler
	@UiHandler("submitBt")
	void onSubmitBtClick(ClickEvent e){
		editUniversity();
	}

	//---------------------------------------------------------------------
	//-------------------------- Server call
	
	private void editUniversity() {
		new ServerCall<Boolean>() {

			@Override
			protected void callService(AsyncCallback<Boolean> asyncCallback) {
				userService.update(panel.getUniversity(),asyncCallback);
			}

			@Override
			public void onSuccess(Boolean success) {
				if(success)
					new MessagePopupPanel("Success","University has well been edited").show();
				else
					new MessagePopupPanel("Error","Operation failed").show();
			}
		}.call();
	}
	
}
